import { Modal } from "@renderer/components/ui/base/modal";
import { SearchField } from "@renderer/components/ui/base/search-field";
import { cn } from "@renderer/lib/utils";
import logger from "@shared/logger/renderer-logger";
import type { McpServer } from "@shared/triplit/types";
import { Check, SearchX, Server } from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import { useFilter } from "react-aria-components";
import { useTranslation } from "react-i18next";

interface McpServerSelectModalProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  selectedServerIds: string[];
  onSelectionChange: (serverIds: string[]) => void;
  mcpServers: McpServer[];
}

export function McpServerSelectModal({
  isOpen,
  onOpenChange,
  selectedServerIds,
  onSelectionChange,
  mcpServers,
}: McpServerSelectModalProps) {
  const { t } = useTranslation("translation", {
    keyPrefix: "chat.tool-bar",
  });

  const { contains } = useFilter({ sensitivity: "base" });
  const [searchQuery, setSearchQuery] = useState("");

  // Filter servers based on search query
  const filteredServers = useMemo(() => {
    if (!searchQuery.trim()) return mcpServers;

    return mcpServers.filter(
      (server) =>
        contains(server.name, searchQuery) ||
        contains(server.description || "", searchQuery) ||
        contains(server.type || "", searchQuery),
    );
  }, [mcpServers, searchQuery, contains]);

  // Handle server selection toggle
  const handleServerToggle = useCallback(
    (serverId: string, checked: boolean) => {
      const server = mcpServers.find((s) => s.id === serverId);

      // Update UI immediately for better responsiveness
      if (checked) {
        onSelectionChange([...selectedServerIds, serverId]);
      } else {
        onSelectionChange(selectedServerIds.filter((id) => id !== serverId));
      }

      // Log the change
      logger.debug(
        "MCP server selection changed, requesting tools update in background",
        {
          serverId,
          serverName: server?.name || "Unknown",
          checked,
        },
      );

      // Request tools refresh in background (non-blocking)
      setTimeout(async () => {
        try {
          const { mcpService } = window.service;
          await mcpService.refreshAllTools();
          logger.debug(
            "MCP tools refreshed in background after server selection change",
            {
              serverId,
              serverName: server?.name || "Unknown",
              checked,
            },
          );
        } catch (error) {
          logger.error("Failed to refresh MCP tools in background", {
            serverId,
            serverName: server?.name || "Unknown",
            checked,
            error,
          });
        }
      }, 0);
    },
    [selectedServerIds, onSelectionChange, mcpServers],
  );

  return (
    <Modal.Content
      className="min-w-[500px]"
      closeButton={false}
      isOpen={isOpen}
      onOpenChange={onOpenChange}
    >
      {/* Search */}
      <div className="p-4 pb-3">
        <SearchField
          className="h-10 rounded-[10px] bg-[#F5F5F5] shadow-none dark:bg-[#1A1A1A]"
          placeholder={t("search-mcp-servers")}
          value={searchQuery}
          onChange={setSearchQuery}
          autoFocus
        />
      </div>

      {/* Server list */}
      <div className="max-h-[400px] min-h-[200px] overflow-y-auto px-4">
        {filteredServers.length > 0 ? (
          <div className="space-y-1">
            {filteredServers.map((server) => {
              const isSelected = selectedServerIds.includes(server.id);
              return (
                <button
                  key={server.id}
                  type="button"
                  className={cn(
                    "flex w-full cursor-pointer items-center space-x-3 rounded-md p-3 text-left transition-colors",
                    isSelected
                      ? "bg-[#F3F2FF] dark:bg-[#49306A]"
                      : "hover:bg-[#F9F9F9] dark:hover:bg-[#1A1A1A]",
                  )}
                  onClick={() => handleServerToggle(server.id, !isSelected)}
                >
                  <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center">
                    {server.icon ? (
                      <span className="text-sm">{server.icon}</span>
                    ) : (
                      <Server className="size-4 text-muted-fg" />
                    )}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="truncate font-medium text-sm">
                      {server.name}
                    </div>
                    {server.description && (
                      <p className="mt-1 truncate text-muted-fg text-xs">
                        {server.description}
                      </p>
                    )}
                  </div>
                  <div className="flex flex-shrink-0 items-center">
                    <div
                      className={cn(
                        "flex h-[18px] w-[18px] items-center justify-center rounded-[6px] border-2",
                        isSelected
                          ? "border-[#8E47F0] bg-[#8E47F0]"
                          : "border-[#D9D9D9] dark:border-[#5C5C5C]",
                      )}
                    >
                      {isSelected && <Check className="h-3 w-3 text-white" />}
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        ) : (
          <div className="flex h-32 flex-col items-center justify-center gap-2 text-muted-fg text-sm">
            <SearchX className="size-8" />
            <p>{t("no-mcp-servers-found")}</p>
          </div>
        )}
      </div>
    </Modal.Content>
  );
}
